import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.iai.v20200303 import iai_client, models

def get_data():
    cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
    httpProfile = HttpProfile()
    httpProfile.endpoint = "iai.tencentcloudapi.com"
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)
    req = models.GetPersonListRequest()
    params = {
        "GroupId": "DLUT"
    }
    req.from_json_string(json.dumps(params))
    resp = client.GetPersonList(req)
    ans = json.loads(resp.to_json_string())
    return ans["PersonInfos"]

def judge_mask(flag,pic):
    if(flag==0):
        cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)

        req = models.DetectFaceRequest()
        params = {
            "MaxFaceNum": 1,
            "Url": pic,
            "NeedFaceAttributes": 1
        }
        req.from_json_string(json.dumps(params))
        resp = client.DetectFace(req)
        ans = json.loads(resp.to_json_string())
        if(ans["FaceInfos"][0]["FaceAttributesInfo"]["Mask"]):
            return True
        else:
            return False
    if(flag==1):
        cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)

        req = models.DetectFaceRequest()
        params = {
            "MaxFaceNum": 1,
            "Url": pic,
            "NeedFaceAttributes": 1
        }
        req.from_json_string(json.dumps(params))
        resp = client.DetectFace(req)
        ans = json.loads(resp.to_json_string())
        if (ans["FaceInfos"][0]["FaceAttributesInfo"]["Mask"]):
            return False
        else:
            return True

def add(face,mask,name,id,gender):
    judge=False
    for i in range(0,len(id)):
        if(id[i]<"0" or id[i]>"9"):
            judge=True
            break
    if(judge):
        return "学号不符合要求"
    if(judge_mask(0,face)):
        return "无口罩图片错误"
    if(judge_mask(1,mask)):
        return "有口罩图片错误"
    all_data = get_data()
    judge=True
    for i in range(0,len(all_data)):
        if(all_data[i]["PersonId"]==id):
            judge=False
            break
    if(judge):
        cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)
        req = models.CreatePersonRequest()
        params = {
            "GroupId": "DLUT",
            "PersonName": name,
            "PersonId": id,
            "Gender": int(gender),
            "Url": face,
            "UniquePersonControl": 2,
            "QualityControl": 0,
            "NeedRotateDetection": 1
        }
        req.from_json_string(json.dumps(params))
        resp = client.CreatePerson(req)

        cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)
        req = models.CreateFaceRequest()
        params = {
            "PersonId": id,
            "Urls": [mask],
            "QualityControl": 0,
            "NeedRotateDetection": 1
        }
        req.from_json_string(json.dumps(params))
        resp = client.CreateFace(req)
        return "成功"
    else:
        cred = credential.Credential("AKIDud9M3U3vKWTO30sUdZK5buyrVzGMqiV2", "QsGSRDmAQoNipiZBdohKhncNs66oGRM2")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = iai_client.IaiClient(cred, "ap-shanghai", clientProfile)
        req = models.CreateFaceRequest()
        params = {
            "PersonId": id,
            "Urls": [face,mask],
            "QualityControl": 0,
            "NeedRotateDetection": 1
        }
        req.from_json_string(json.dumps(params))
        resp = client.CreateFace(req)
        return "成功"

import base64
import uuid
from PIL import Image
import os

def get_name():
    uuid_str = uuid.uuid4().hex
    file_name = uuid_str + ".png"
    return file_name

def base_url(word):
    base = word.replace(' ','+')
    imgdata = base64.b64decode(base)
    name = get_name()
    print(name)
    path = "Pic/"+name
    file = open(path, 'wb')
    file.write(imgdata)
    file.close()

    imagefile = "./Pic/" + name
    img = Image.open(imagefile)  # 返回一个Image对象

    # os模块中的path目录下的getSize()方法获取文件大小，单位字节Byte
    size = os.path.getsize(imagefile)  # 计算图片大小即KB
    # size的两个参数
    width, height = img.size[0], img.size[1]
    # 用于保存压缩过程中的temp路径,每次压缩会被不断覆盖
    newPath = './Pic/temp.jpg'
    while size > 1024 * 1024 * 5:
        width, height = round(width * 0.9), round(height * 0.9)
        print(width, height)
        img = img.resize((width, height), Image.ANTIALIAS)
        img.save(newPath)
        size = os.path.getsize(newPath)
    # 压缩完成
    img.save(imagefile)
    return "https://pic.cpolar.cn/"+name